<?php
namespace app\common\model;

use think\Model;
use think\Session;

class User extends Model
{

    public function auths()
    {
        return $this->belongsToMany('Auth', 'user_auth', 'auth_id', 'user_id');
    }


    public function projects()
    {
        return $this->hasMany('Project', 'person', 'id');
    }

    /**
     * 获取用户拥有项目的数量
     * @return int|string
     * @throws \think\Exception
     */
    public function user_project_count()
    {
        return $this->projects()->count();
    }

    /**
     * 判断用户对某项目是否有对应的权限
     * @param $project_id   项目id
     * @param $operation, 操作类型'list', 'update', 'delete'
     * @return bool
     * @throws \think\exception\DbException
     */
    public function hasPermission($project_id, $operation='list')
    {
        if (session('is_super')){
            return true;
        }

        $res = $this->projects()->field('id')->select();
        // 如果是项目开发人员，则拥有权限
        foreach ($res as $re) {
            if ($re->id == $project_id){
                return true;
            }
        }

        // if(in_array($project_id, $res)){
        //     print_r("hahahha");
        // }

        $operation_map = array('list'=>'1', 'update'=>'2', 'delete'=>'3');
        if (!array_key_exists($operation, $operation_map)){
            return false;
        }

        $project = Project::get($project_id);
        $pname = $project['pname'];
        $permissions = session('permissions');
        // print_r($permissions);
        if (array_key_exists($pname, $permissions)){
            foreach ($permissions as $permission) {
                // print_r($permission);
                // 遍历每一个角色，查找是否有该项目operation的权限
                if(in_array($operation_map[$operation], $permissions[$pname])){
                    return true;
                }else{
                    continue;
                }
            }
        }

        return false;

    }

}